package com.ayun.base;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * @author 斌叔
 * @description: 解析 jwt 令牌
 * @create 2022-05-09 13:23
 */
public class TestCreateJwt {


    public static void main(String[] args) {
        String token = createJwt();
        System.out.println(token);
        parseJwt(token);
    }

    //生成token
    public static String createJwt() {
        // 当前时间毫秒数
        long now = System.currentTimeMillis();
        //过期时间为60秒
        long exp = now + 1000*10*6;

        JwtBuilder builder = Jwts.builder().setId("1")  //jwt的唯一id
                .setSubject("admin")  //主题
                .setIssuedAt(new java.util.Date()) //签发时间
                .signWith(SignatureAlgorithm.HS256, "123456")//签名算法和密钥,修改为自己的密钥
                .setExpiration(new Date(exp));

        return builder.compact();
    }

    //解析token
    public static void parseJwt(String token) {

        Claims claims = Jwts.parser().setSigningKey("123456") //签名算法和密钥
                .parseClaimsJws(token)
                .getBody();
        System.out.println(claims.getId());
        System.out.println(claims.getSubject());
    }
}
